import { history, Link } from '@@/exports';

import styles from './index.less';
import Footer from '@/components/Footer';
import {Alert,  message, Tabs} from 'antd';
import React, { useState } from 'react';
import { LoginForm, ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import {randomStr} from "@antfu/utils";
import { LockOutlined, MobileOutlined, UserOutlined} from "@ant-design/icons";
import {getEmailCaptcha, userEmailRegister} from "@/services/shApi-backend/userController";

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Register: React.FC = () => {
  const [imageUrl, setImageUrl] = useState<any>(null);

  React.useEffect(async () => {
    await getCaptcha();
    return () => {
      //return出来的函数本来就是更新前，销毁前执行的函数，现在不监听任何状态，所以只在销毁前执行
    };
  }, []); //第二个参数一定是一个空数组，因为如果不写会默认监听所有状态，这样写就不会监听任何状态，只在初始化时执行一次。

  /**
   * 获取图形验证码
   */
  const getCaptcha = async () => {
    let randomString;
    const temp = localStorage.getItem('api-open-platform-randomString');
    if (temp) {
      randomString = temp;
    } else {
      randomString = randomStr(
        32,
        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
      );
      localStorage.setItem('api-open-platform-randomString', randomString);
    }
    //携带浏览器请求标识
    // const res = await getCaptchaUsingGET({
    //   headers: {
    //     signature: randomString,
    //   },
    //   responseType: 'blob', //必须指定为'blob'
    // });
    // let url = window.URL.createObjectURL(res);
    // setImageUrl(url);
  };

  const handleSubmit = async (values: API.UserRegisterRequest) => {
    const { userPassword, checkPassword } = values;
    console.log(values)
    if (userPassword !== checkPassword) {
      message.error('两次输入密码不一致');
      return;
    }
    try {
      const signature = localStorage.getItem("api-open-platform-randomString")
      // 注册
       const res = await userEmailRegister(values,);
      console.log(res)
      if (res.data) {
        const defaultLoginSuccessMessage = '注册成功！';
        message.success(defaultLoginSuccessMessage);
        /** 此方法会跳转到 redirect 参数所在的位置 */

        if (!history) return;
        history.push('/user/login');
        return;
      }
    } catch (error: any) {
      console.log(error);
      message.error(error.message);
    }
  };
  const [userRegisterState, setUserRegisterState] = useState<API.RegisterResult>({});
  const { status, type: registerState } = userRegisterState;

  const [type, setType] = useState<string>('register');

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          submitter={{
            searchConfig: {
              submitText: '注册',
            },
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="SH-API"
          subTitle={
            <>
              <p>
                <b>一个丰富的API开放调用平台</b>
              </p>
            </>
          }
          onFinish={async (values) => {
            await handleSubmit(values as API.UserRegisterRequest);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'register',
                label: '账号密码注册',
              },
            ]}
          />
          {status === 'error' && registerState === 'register' && (
            <LoginMessage content={'错误的用户名和密码(admin/ant.design)'} />
          )}
          {type === 'register' &&
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'账号：账号应大于3个字小于16个字'}
                rules={[
                  {
                    required: true,
                    pattern:/^.{3,16}$/,
                    message: '账号必须大于3个字符并且小于16个字符！',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'密码: 至少3位'}
                rules={[
                  {
                    required: true,
                    pattern:/^.{3,16}$/,
                    message: '密码必须大于3个字符且小于16个字符！',
                  },
                ]}
              />
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'确认密码'}
                rules={[
                  {
                    required: true,
                    pattern:/^.{3,16}$/,
                    message: '两次密码必须一致！',
                  },
                ]}
              />

              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={'prefixIcon'} />,
                }}
                name="email"
                placeholder={'邮箱'}
                rules={[
                  {
                    required: true,
                    message: '请输入邮箱号！',
                  },
                ]}
              />

              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码！'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="emailCaptcha"
                phoneName="email"
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
                onGetCaptcha={async (email) => {
                  const result = await getEmailCaptcha({
                    email,
                  });
                  if (result === false) {
                    return;
                  }
                  message.success(result.data);
                }}
              />

            </>
          }

          {status === 'error' && registerState === 'emailRegister' && <LoginMessage content="验证码错误" />}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <Link
              style={{
                marginBottom: 24,
                float: 'right'
              }}
              to={'/user/login'}
            >
              已有帐号，去登陆！
            </Link>
          </div>

        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Register;
